package com.buaa.rental.AdminController;

import com.buaa.rental.Dao.CommonRep;
import com.buaa.rental.Dao.Repair;
import com.buaa.rental.Dao.User;
import com.buaa.rental.Service.RepairService;
import com.buaa.rental.Service.UserService;
import com.buaa.rental.Util.CodeException;
import com.buaa.rental.Util.MyAnnotations.Authorization;
import com.buaa.rental.Util.MyAnnotations.CurrentUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/worker/")
public class WorkerRepairController {
    @Autowired
    private RepairService repairService;

    @Authorization(role = User.Role.worker)
    @GetMapping("getAllRepair")
    public CommonRep getRepairs(@CurrentUser User user) {
        CommonRep rep = new CommonRep();
        rep.setData(repairService.getRepairByWorker(user.uid));
        return rep;
    }

    @Authorization(role = User.Role.worker)
    @PostMapping("addMessage")
    public CommonRep addMessage(@CurrentUser User user, @RequestBody Map<String, Object> map) throws CodeException {
        long rid = Integer.parseInt((String) map.get("rid"));
        Repair repair = repairService.getRepairById(rid);
        if (repair.workerId != user.uid) {
            throw new CodeException("102", "用户无权访问！");
        }
        Repair.Message message = new Repair.Message();
        message.uid = user.uid;
        message.text = (String) map.get("text");
        message.photos = (List<String>) map.get("photos");
        repairService.addMessage(repair, message);
        return new CommonRep();
    }

}
